<?php

namespace App\Services;

//百融风控
use App\Models\MemberLegal;
use App\Models\Order;
use App\Models\OrderRemark;

class BairaongService
{
    public function AESEncrypt($data, $key)
    {
        $key = $this->SHA1PRNG($key);
        $result = openssl_encrypt($data, "AES-128-ECB",  $key, OPENSSL_RAW_DATA);
        return $this->EncodeBase64URLSafeString($result);
    }
    public function SHA1PRNG($key){
        return substr(openssl_digest(openssl_digest($key, "sha1", true), "sha1", true), 0, 16);
    }
    public function EncodeBase64URLSafeString($result){
        return str_replace(['+','/','='], ['-','_',''], base64_encode($result));
    }


    /**
     * 信息验证规则-法院信息详情个人高级版
     * @param $post
     * @param $order_id
     * @return array|false|\Illuminate\Database\Eloquent\Builder|void
     */
    public  function limitQuery($post=[],$order_id=0)
    {
        $array=[];
        $array['authId']=1;
        $array['isCpt']=1;
        $array['name']=$post['cert_name'];
        $array['idcard']=$post['cert_no'];
        $array['mobile']=$post['mobile'];
        $uid=$post['id']??0;
        $res=MemberLegal::query($post['cert_no']);
        if($res){
            self::addLog('百融法诉查询',$array,$res);

            if(!$res['is_legal']&&$order_id){
                Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                $add_remark = [
                    'uid'=>'23',
                    'username'=>'法诉',
                    'create_time'=>time(),
                    'remark'=>'机构查询出用户法诉',
                    'order_id'=>$order_id
                ];
                OrderRemark::insert($add_remark);
            }
            return $res;
        }else{
            $res=self::RequestInfoverify($array);
            self::addLog('百融法诉查询',$array,$res);
            $result=json_decode($res,true);
            if(!isset($result['code'])||$result['code']!='00'){
                return false;
            }
            if(isset($result['CourtDetailPro'])&&isset($result['InfoVerification'])
                &&isset($result['InfoVerification']['hit_rules']['rule_c_courtdetailpro'])
                &&(isset($result['InfoVerification']['hit_rules']['rule_c_courtdetailpro']['FAM011'])
                ||isset($result['InfoVerification']['hit_rules']['rule_c_courtdetailpro']['FAM010'])
                ||isset($result['InfoVerification']['hit_rules']['rule_c_courtdetailpro']['FAM022'])
                )
            ){
                if($order_id){
                    Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                    $add_remark = [
                        'uid'=>'23',
                        'username'=>'法诉',
                        'create_time'=>time(),
                        'remark'=>'机构查询出用户法诉',
                        'order_id'=>$order_id
                    ];
                    OrderRemark::insert($add_remark);
                }
                MemberLegal::insertMemberLegal($post['cert_no'],$post['cert_name'],$post['mobile'],$uid,0,$res);
            }else{
                MemberLegal::insertMemberLegal($post['cert_no'],$post['cert_name'],$post['mobile'],$uid,1,$res);
            }
        }
    }


    /**
     * 贷前策略反欺诈规则-借贷意向验证-通用
     * @param $post
     * @param $order_id
     * @return array|false|\Illuminate\Database\Eloquent\Builder|void
     */
    public  function loanQuery($post=[],$order_id=0)
    {
        $array=[];
        $array['authId']=1;
        $array['isCpt']=1;
        $array['name']=$post['cert_name'];
        $array['idcard']=$post['cert_no'];
        $array['mobile']=$post['mobile'];
        $uid=$post['id']??0;
        $res=MemberLegal::query($post['cert_no']);
        if($res){
            self::addLog('百融法诉查询',$array,$res);

            if(!$res['is_legal']&&$order_id){
                Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                $add_remark = [
                    'uid'=>'23',
                    'username'=>'法诉',
                    'create_time'=>time(),
                    'remark'=>'机构查询出用户法诉',
                    'order_id'=>$order_id
                ];
                OrderRemark::insert($add_remark);
            }
            return $res;
        }else{
            $res=self::RequestInfoverify($array);
            self::addLog('百融法诉查询',$array,$res);
            $result=json_decode($res,true);
            if(!isset($result['code'])||$result['code']!='00'){
                return false;
            }
            if( isset($result['ExecutionLimited'])
                &&isset($result['ExecutionLimited']['xg1'])
                &&isset($result['ExecutionLimited']['xg1']['signalRating'])
                &&$result['ExecutionLimited']['xg1']['signalRating']<=3
            ){
                if($order_id){
                    Order::where('id',$order_id)->update(['status'=>OrderService::ORDER_STATUS_CENCEL]);
                    $add_remark = [
                        'uid'=>'23',
                        'username'=>'法诉',
                        'create_time'=>time(),
                        'remark'=>'机构查询出用户法诉',
                        'order_id'=>$order_id
                    ];
                    OrderRemark::insert($add_remark);
                }
                MemberLegal::insertMemberLegal($post['cert_no'],$post['cert_name'],$post['mobile'],$uid,0,$res);
            }else{
                MemberLegal::insertMemberLegal($post['cert_no'],$post['cert_name'],$post['mobile'],$uid,1,$res);
            }
        }
    }
    public  function RequestInfoverify($data){
        $apiCode='3033917';
        $appKey='c22e562c4af2670bfb9bb8e166429591b05dd7019000e706e42fdffa20a1f5b6';
        $appKey_hash = hash("sha256", $appKey);
        $data=[
            'id'=>hash("sha256", $data['idcard']),
            'cell'=>hash("sha256", $data['mobile']),
            'name'=>$data['name'],
            'conf_id'=>'MCP_BR0004393',
        ];
        $jsonDataCode = $jsonData=stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE));
        $jsonDataAES = $this->AESEncrypt($jsonDataCode, $appKey);
        $checkCodeHash = hash("sha256", $jsonDataCode.$apiCode.$appKey);
        $post = array(
            'apiCode' => $apiCode,
            'appKey' => $appKey_hash,
            'jsonData' => $jsonDataAES,
            'checkCode' => $checkCodeHash,
        );
//        var_dump($post);
        $url = "https://api2.100credit.cn/infoverify/v3/info_verify";
        $ch = curl_init();
        $httpheader[] = "content-type:application/x-www-form-urlencoded";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }

    public function Request($data){
        $apiCode='3033917';
        $appKey='c22e562c4af2670bfb9bb8e166429591b05dd7019000e706e42fdffa20a1f5b6';
        $appKey_hash = hash("sha256", $appKey);
        $data=[
            'id'=>hash("sha256", $data['idcard']),
            'cell'=>hash("sha256", $data['mobile']),
            'name'=>$data['name'],
            'conf_id'=>'STR_BR0009251',
        ];
        $jsonDataCode = $jsonData=stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE));
        $jsonDataAES = $this->AESEncrypt($jsonDataCode, $appKey);
        $checkCodeHash = hash("sha256", $jsonDataCode.$apiCode.$appKey);
        $post = array(
            'apiCode' => $apiCode,
            'appKey' => $appKey_hash,
            'jsonData' => $jsonDataAES,
            'checkCode' => $checkCodeHash,
        );
//        var_dump($post);
        $url = "https://api2.100credit.cn/strategy_api/v3/hx_query";
        $ch = curl_init();
        $httpheader[] = "content-type:application/x-www-form-urlencoded";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);

        self::addLog('百融法诉查询q',$data,$result);
        return $result;
    }

    public static function addLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::debug($message,$content);
    }

}
